// ESP8266
#include <ESP8266.h>
#ifdef ESP8266_USE_SOFTWARE_SERIAL
SoftwareSerial mySerial_8266(A0, A1); 
ESP8266 wifi(mySerial_8266, 9600);
#else
ESP8266 wifi(Serial1, 9600);
#endif
#define HOST_NAME   "192.168.1.10"   //server ip
#define HOST_PORT   (80)
String MAC = "";
String IP  = "";

#include "dht11.h"
dht11 dht11_0;
#define DHT11PIN_0 A3               // dht11 data pin

#define TIME_STEP  120              // Data transmission interval (s)
unsigned long t_loop;
boolean b_con = false;

void setup() {
  Serial.begin(9600);
  t_loop = millis();
}

void loop() {

  // your sensor
  dht11_0.read(DHT11PIN_0);
  float dht_h0 = (float)dht11_0.humidity;
  float dht_t0 = (float)dht11_0.temperature;

  float t_s = ( millis() - t_loop) / 1000;

  Serial.print("humidity:");
  Serial.print(dht_h0, 0);
  Serial.print("; ");

  Serial.print("temperature:");
  Serial.print(dht_t0, 0);
  Serial.print("; ");

  Serial.print("delay:");
  Serial.print( t_s );
  Serial.println();
  
  if ( t_s > TIME_STEP) {
#ifdef ESP8266_USE_SOFTWARE_SERIAL
    mySerial_8266.listen();
#endif
    b_con = wifi.createTCP(HOST_NAME, HOST_PORT);
    Serial.print("con:");
    Serial.print(b_con?"true":"false");
    if (!b_con) {
      wifi.restart();
      Serial.println();
      t_loop = millis();
      return;
    }
    
    // post data
    postData("dht11_temp",      dht_t0 );
    postData("dht11_humidity",  dht_h0 );
    
    b_con = !wifi.releaseTCP();
    Serial.print("; close:");
    Serial.println(!b_con?"true":"false");
    t_loop = millis();
  }

  delay(5000);
}

void postData(String key, float val) {
  if (b_con) {

    String s = "POST /weather/main.php?cmd=setdata&key="
       + key + "&val=" + String(val) + " HTTP/1.1\r\n"
       + "Host: " + String(HOST_NAME) + "\r\n"
       + "Content-Length: 0\r\n"
       + "\r\n"
       + "\r\n";
    char c[s.length()];
    s.toCharArray(c, s.length());
    char *_p = c;
    wifi.send((const uint8_t*)_p, strlen(_p));
    delay(1000);

  } else {
    Serial.print("create tcp err\r\n");
  }

}
